package com.exartisan.molisasurvey;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.exartisan.bean.User;

public class InputInfoActivity extends BaseActivity {
	private EditText edtUserName;
	private EditText edtChidoan;
	private EditText edtMobile;
	private EditText edtEmail;
	private Spinner spinerDonvi;
	private DatePicker datePicker;
	private EditText edtBirthday;
	private Button btnChooseDate;
	private int year;
	private int month;
	private int day;
	private String birthday;

	static final int DATE_DIALOG_ID = 999;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_input_info);
	}

	@Override
	protected void initViews() {
		edtUserName = (EditText) findViewById(R.id.edtUserName);
		edtChidoan = (EditText) findViewById(R.id.edtChidoan);
		edtMobile = (EditText) findViewById(R.id.edtSDT);
		edtBirthday = (EditText) findViewById(R.id.edtNgaySinh);
		spinerDonvi = (Spinner) findViewById(R.id.spinner1);
		edtEmail = (EditText) findViewById(R.id.edtEmail);
		watchText(edtUserName, 0);
		watchText(edtChidoan, 0);
		watchText(edtMobile, 2);
		watchText(edtBirthday, 0);
		watchText(edtEmail, 1);
		addListenerOnButton();
	}

	@Override
	protected void initVariables() {
	}

	@Override
	protected void initActions() {
		findViewById(R.id.layout_input_info).setOnTouchListener(
				new OnTouchListener() {

					public boolean onTouch(View v, MotionEvent event) {
						hideSoftKeyboard();
						return false;
					}
				});
		findViewById(R.id.scroll_info).setOnTouchListener(
				new OnTouchListener() {

					public boolean onTouch(View v, MotionEvent event) {
						hideSoftKeyboard();
						return false;
					}
				});
	}

	public void onClickAccept(View view) {
		String surveyName = "phan1";
		String username = edtUserName.getText().toString();
		String chidoan = edtChidoan.getText().toString();
		String mobile = edtMobile.getText().toString();
		String donvi = spinerDonvi.getSelectedItem().toString();
		String email = edtEmail.getText().toString();
		String birthday = edtBirthday.getText().toString();
		String log = "";
		String log1 = "";
		String log2 = "";
		User user = new User();
		user = getUser();
		String value[] = new String[] { mobile, email, username, chidoan,
				donvi, birthday };
		for (int i = 0; i < value.length; i++) {
			if (validate(0, value[i]) == false)
				log = "Nhập thiếu thông tin";
			if (validate(2, value[0]) == false)
				log1 = "Sai sdt";
			if (validate(1, value[1]) == false)
				log2 = "Sai địa chỉ email";
		}
		if (log.equals("Nhập thiếu thông tin") || log1.equals("Sai sdt")
				|| log2.equals("Sai địa chỉ email")) {
			String msg = "Kiếm tra lại thông tin";
			AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(
					this);
			restartAlertBuilder.setTitle("Thông báo");
			restartAlertBuilder.setMessage(msg);
			restartAlertBuilder.setCancelable(false);
			restartAlertBuilder.setPositiveButton("Ok", null);
			AlertDialog restartAlertDialog = restartAlertBuilder.create();
			restartAlertDialog.show();
		} else {
			user.setUserName(username);
			user.setChidoan(chidoan);
			user.setMobile(mobile);
			user.setDonvi(donvi);
			user.setEmail(email);
			user.setBirthday(birthday);
			log = "";
			log1 = "";
			log2 = "";
			Intent intent = new Intent(this, SurveyActivity.class);
			intent.putExtra("surveyName", surveyName);
			startActivity(intent);
		}
		;
	}

	public void addListenerOnButton() {

		btnChooseDate = (Button) findViewById(R.id.btNS);

		btnChooseDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showDialog(DATE_DIALOG_ID);

			}

		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			datePicker = new DatePicker(getApplicationContext());
			final Calendar c = Calendar.getInstance();
			year = 1990;
			month = 01;
			day = 01;
			datePicker.init(year, month, day, null);
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			// edtBirthday.setText((month + 1)+"-"+day+"-"+year);
			birthday = (month + 1) + "-" + day + "-" + year;
			edtBirthday.setText(birthday);
			// Log.d("birthday",birthday);
			// set selected date into datepicker also
			datePicker.init(year, month, day, null);

		}
	};

	private void hideSoftKeyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) this
				.getSystemService(SherlockActivity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
				.getWindowToken(), 0);
	}

	private void watchText(final EditText edt, final int type) {
		edt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (validate(type, s.toString()) == false) {
					edt.setBackgroundColor(Color.RED);
				} else
					edt.setBackgroundResource(R.drawable.edit_text_holo_light);
			}
		});
	}

	private boolean validate(int type, String data) {
		String[] prefix = new String[] { "090", "093", "0120", "0121", "0122",
				"0126", "0128", "096", "097", "098", "0163", "0164", "0165",
				"0166", "0167", "0168", "0169", "091", "094", "0123", "0124",
				"0125", "0127", "0129", "092", "0188", "095", "0993", "0994",
				"0995", "0996", "0199" };
		switch (type) {
		case 1: // email
			String regexEmail = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
					+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
			Pattern pattern = Pattern.compile(regexEmail);
			Matcher matcher = pattern.matcher(data);
			if (matcher.find())
				return true;
			else
				return false;
		case 2: // mobile
			for (int i = 0; i < prefix.length; i++) {
				if (data.contains(prefix[i])) {
					if (prefix[i].length() == 3 && data.length() == 10)
						return true;
					else if (prefix[i].length() == 4 && data.length() == 11)
						return true;
					else return false;
				}
			}
			return false;
		default:
			if (data.equals(""))
				return false;
			else
				return true;
		}

	}
	
	@Override
	public void onBackPressed() {
		getUser().setData(null);
		super.onBackPressed();
	}

}
